package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    private LoginService loginService;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping("/check")
    public Result check(HttpServletResponse response ,@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String key = telephone+ "_" +  RedisMessageConstant.SENDTYPE_LOGIN;
        String codeInRedis = jedisPool.getResource().get(key);
        boolean ismember = loginService.checkIsMember(telephone);
        if (!ismember){
            //如果不是会员则默认注册会员
            Member member = new Member();
            member.setName(telephone);
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            loginService.register(member);
        }

        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);//有效期30天
        response.addCookie(cookie);

        System.out.println(key+"   缓存的redis的值:"+codeInRedis);
        if (codeInRedis!=null&&validateCode.equals(codeInRedis)){
            return new Result(true,"登录成功");
        }
        return new Result(false,"验证码错误");
    }

}
